package com.gs.gms.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * Utility to manipulate objects.
 * 
 * @author Sabuj.das
 *
 */
public class ObjectUtil {

	/**
	 * Creates getter method name from the field name.
	 * @param fieldName
	 * @return
	 */
	public static String getGetterMethod(String fieldName){
		if(StringUtil.hasValidContent(fieldName)){
			if(fieldName.length() > 1)
				return "get" + (""+fieldName.charAt(0)).toUpperCase() + fieldName.substring(1);
			return "get" + (""+fieldName.charAt(0)).toUpperCase();
		}
		return "";
	}
	
	/**
	 * Create a copy of the goven object. This method is only to create 
	 * a copy of data contained in the object and create a new instance
	 * with those data.
	 * 
	 * @param from T
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static <T> T copyOf(T from) throws InstantiationException,
			IllegalAccessException, NoSuchMethodException,
			IllegalArgumentException, InvocationTargetException {
		if (null == from)
			return null;

		Class<T> clazz = (Class<T>) from.getClass();
		T newObject = clazz.newInstance();
		if (null == newObject)
			return null;

		Method[] methods = clazz.getDeclaredMethods();
		if (null != methods) {
			for (int i = 0; i < methods.length; i++) {
				Method getterMethod = methods[i];
				final String name = getterMethod.getName();

				if (name.startsWith("get")) {
					String setter = "set"
							+ name.substring(name.indexOf("get")
									+ "get".length());
					Method setterMethod = clazz.getMethod(setter,
							getterMethod.getReturnType());
					setterMethod.invoke(newObject,
							getterMethod.invoke(from, null));
				}
			}
		}

		return newObject;
	}

}
